<template>
	<view class="technician-pages-order" :style="{background:pageColor}">

		<block v-if="!configInfo.plugAuth.dispatchother">
			<abnor type="NOT_AUTH" :isCenter="true"></abnor>
		</block>
		<block v-if="configInfo.plugAuth.dispatchother">
			
			<view @tap.stop="goDetail(index)" class="list-item fill-base radius-16" v-for="(item,index) in list.data"
				:key="index">
				<view class="nav-title flex-between f-paragraph"
					:class="[{'danger':item.pay_type==2},{'warning':item.pay_type>2&&item.pay_type<6},{'success':item.pay_type==6}]">
					<view class="flex-y-center text-bold"><i class="iconfont iconshijian5 text-normal mr-sm"></i> 预约
						{{$util.formatTime(item.start_time*1000, 'YY-M-D h:m')}}
					</view>
					<view>待接单</view>
				</view>
				<view style="padding:0 28rpx">
					<view class="flex-between f-paragraph c-title pt-md mb-md">
						<view class="f-title text-bold ellipsis max-400">
							{{item.ser_name}}
						</view>
						<view class="flex-y-center">
							<view><span class="font-num">¥</span>{{item.ser_total_price}}</view>
						</view>
					</view>
					<view class="count-list flex-center">
						<view class="count-item">
							<view class="flex-y-baseline f-mini-title font-num">
								<view class="f-md-title">
									{{item.time_long}}
								</view>
								分钟
							</view>
							<view class="f-desc c-caption">服务时长</view>
						</view>
						<view class="count-item">
							<view class="flex-y-baseline f-mini-title font-num">¥<view class="f-md-title">
									{{item.ser_price || 0}}
								</view>
							</view>
							<view class="f-desc c-caption">单价</view>
						</view>
						<view class="count-item">
							<view class="flex-y-baseline f-mini-title font-num">
								¥
								<view class="f-md-title">
									{{item.ser_total_price || 0}}
								</view>
							</view>
							<view class="f-desc c-caption" >预估收益</view>
						</view>
					</view>

					<view class="flex-between pt-lg pb-lg">
						<view class="flex-y-center f-paragraph c-title"><i class="iconfont icondizhi31"
								:style="{color:'#43A960',fontSize:'36rpx'}"></i>
							<view style="margin: 0 4rpx;">距离</view>
							<view>{{item.distance | hannelDistance}}</view>
						</view>
						<view class="flex-warp">
							<!-- // pay_type 2待接单，5待服务，6服务中，7已完成 -->
							<!-- 待接单 -->
							<block v-if="item.pay_type == 2">
								<view @tap.stop="toRefuse(index)" class="oper-btn sm flex-center f-mini-title c-title" 
								:style="{color: primaryColor,borderColor:primaryColor}">拒单</view>
								<view @tap.stop="toConfirm(index,3)" class="oper-btn flex-center f-mini-title c-base"
									:style="{background:primaryColor,borderColor:primaryColor}">接单</view>
							</block>
						</view>
					</view>
				</view>
			</view>

			<load-more :noMore="list.current_page>=list.last_page&&list.data.length>0" :loading="loading">
			</load-more>
			<abnor v-if="!loading&&list.data.length<=0&&list.current_page==1" :isCenter="true"
				:tip="[{text: '暂无订单数据'}]">
			</abnor>
			<!-- space-max-footer 不可删除 -->
			<view class="space-max-footer"></view>
			<view :style="{height: `${configInfo.tabbarHeight}px`}"></view>
			<longbingbing-tabbar tabType="coachTabBar" :cur="5"></longbingbing-tabbar>
		</block>

		<uni-popup ref="refuse_item" type="center" :custom="true">
			<view class="common-popup-content fill-base pd-lg radius-34">
				<view class="title">拒绝接单</view>
				<view class="desc">请确认是否拒接接单</view>
				<textarea v-model="coach_refund_text" class="pd-lg textarea f-desc c-title mt-lg radius-20"
					maxlength="200" placeholder="请输入拒单原因" placeholder-class="f-desc c-caption"></textarea>
				<view class="flex-center mt-md" style="width: 540rpx">
					<view class="flex-1"></view>
					<view>{{coach_refund_text.length>200?200:coach_refund_text.length}}/200</view>
				</view>
				<view class="button">
					<view @tap.stop="$refs.refuse_item.close()" class="item-child">取消</view>
					<view @tap.stop="confirmRefuse" class="item-child c-base"
						:style="{background: primaryColor,color:'#fff'}">确定</view>
				</view>
			</view>
		</uni-popup>

		<!-- #ifdef H5 -->
		<block v-if="configInfo.plugAuth.recording && configInfo.service_recording_show">
			<media-recorder ref="recorder" @success='handlerSuccess' @save="handlerOnSave"
				@error='handlerError'></media-recorder>
		</block>
		<!-- #endif -->

		<!-- #ifdef MP-WEIXIN -->
		<user-privacy ref="user_privacy" :show="false"></user-privacy>
		<!-- #endif -->

	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	import longbingbingLocationFail from "@/components/longbingbing-location-fail.vue"
	// #ifdef H5
	import MediaRecorder from '@/components/media-recorder.vue'
	// #endif
	// #ifndef H5
	var recorderManager = null
	// #endif
	export default {
		components: {
			longbingbingLocationFail,
			// #ifdef H5
			MediaRecorder
			// #endif
		},
		data() {
			return {
				list: {
					data: []
				},
				loading: true,
				coach_refund_text: '',
				lockTap: false,
				param: {
					page: 1
				},
				// #ifndef H5
				isReset: false,
				duration_time: 600
				// #endif
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			isUserMedia: state => state.order.isUserMedia,
			recorder: state => state.order.recorder,
			recorder_status: state => state.order.recorder_status,
			recorder_order_id: state => state.order.recorder_order_id,
			order_unix_list: state => state.order.order_unix_list,
		}),
		async onLoad(options) {
			await this.getCoachInfo()
			this.initIndex()
		},
		// #ifdef H5
		destroyed() {
			// #endif
			// #ifndef H5
			onUnload() {
					// #endif
					this.toUnload()
				},
				filters: {
					hannelDistance(val){
						return (val / 1000).toFixed(2) + 'km'
					}
				},
				async onPullDownRefresh() {
						// #ifndef APP-PLUS
						uni.showNavigationBarLoading()
						// #endif
						this.initRefresh()
						uni.stopPullDownRefresh()
					},
					onReachBottom() {
						if (this.list.current_page >= this.list.last_page || this.loading) return;
						this.param.page = this.param.page + 1;
						this.loading = true;
						this.getList();
					},
					methods: {
						...mapActions(['getConfigInfo', 'toPlayAudio', 'getCoachInfo']),
						...mapMutations(['updateUserItem', 'updateOrderItem']),
						async initIndex(refresh = false) {
							if (!this.configInfo.id || refresh || !this.userInfo.id) {
								await this.getConfigInfo()
							}
							await this.getList()
							this.$util.setNavigationBarColor({
								bg: '#ffffff',
								color: '#000000'
							})
							if (refresh) return
							// #ifndef H5
							recorderManager = uni.getRecorderManager()
							//开始录音
							recorderManager.onStart(() => {
								this.$util.log('开始录音')
							})
							//结束录音
							recorderManager.onStop((res) => {
								this.$util.log('结束录音', res)
								this.handlerOnSave(res)
								let {
									duration
								} = res
								let currentTime = parseInt(duration / 1000)
								let isReset = this.duration_time * 1 - currentTime > 1 ? false : true
								this.isReset = isReset
								if (isReset) {
									this.handlerOnChanger()
								}
							})
							// 录音异常
							recorderManager.onError((e) => {
								this.$util.log('录音异常', e)
							})
							// #endif

							// #ifdef MP-WEIXIN
							let privacyCheck = this.$refs.user_privacy.check()
							if (privacyCheck) {
								this.$refs.user_privacy.open()
								return
							}
							// #endif

							// #ifdef H5
							if (!refresh) {
								let {
									status: coach_status = 0,
									coach_position = 0
								} = this.userCoachStatus
								if (coach_position && coach_status == 2) {
									this.$util.getCoachUtilLoca()
									this.$jweixin.hideOptionMenu()
								} else {
									this.$jweixin.initJssdk(() => {
										this.$jweixin.hideOptionMenu()
									})
								}
							}
							// #endif
						},
						initRefresh() {
							uni.pageScrollTo({
								duration: 0,
								scrollTop: 0
							})
							this.param.page = 1
							this.initIndex(true)
						},
						async getList(flag = false) {
							let {
								list: oldList,
								param,
								coachInfo
							} = this
							let {
								lat,
								lng
							} = coachInfo
							param.lat = lat
							param.lng = lng
							let newList = await this.$api.technician.taskHall(param)
							if (this.param.page == 1) {
								this.list = newList
							} else {
								newList.data = oldList.data.concat(newList.data)
								this.list = newList
							}
							this.loading = false
							this.$util.hideAll()
						},
						async toUnload() {
							this.updateOrderItem({
								key: 'recorder_status',
								val: false
							})
							this.updateOrderItem({
								key: 'recorder_order_id',
								val: 0
							})
						},
						// 开始录音
						async handlerOnChanger() {
							// #ifdef MP-WEIXIN
							let privacyCheck = this.$refs.user_privacy.check()
							if (privacyCheck) {
								this.$refs.user_privacy.open()
								return
							}
							// #endif
							// #ifndef H5
							await this.$util.checkAuth({
								type: "record"
							});
							// #endif
							let {
								recorder_status,
								duration_time
							} = this
							if (recorder_status) {
								// #ifdef H5
								this.$refs.recorder.stop()
								// #endif
								// #ifndef H5
								recorderManager.stop()
								// #endif
							} else {
								// #ifdef H5
								this.$refs.recorder.start()
								// #endif
								// #ifndef H5
								recorderManager.start({
									format: 'mp3',
									duration: duration_time * 1000,
								})
								// #endif
							}
							this.updateOrderItem({
								key: 'recorder_status',
								val: !recorder_status
							})
						},
						async handlerOnEnd() {
							// #ifdef H5
							this.$refs.recorder.stop()
							setTimeout(() => {
								this.handlerOnSave()
							}, 1000)
							// #endif
							// #ifndef H5
							recorderManager.stop()
							// #endif
							this.updateOrderItem({
								key: 'recorder_status',
								val: false
							})
						},
						async handlerOnSave(res = {}) {
							this.$util.showLoading({
								title: `录音上传中`
							})
							let filePath = ''
							// #ifdef H5
							let unix = parseInt(new Date().getTime() / 1000)
							let name = `服务过程录音-${unix}.mp3`
							let {
								data
							} = this.recorder
							let file = new File([data], name, {
								type: 'audio/mp3'
							})
							filePath = URL.createObjectURL(file)
							// #endif
							// #ifndef H5
							let {
								tempFilePath,
							} = res
							filePath = tempFilePath
							// #endif

							let {
								attachment_path: link
							} = await this.$api.base.uploadFile({
								filePath,
								formData: {
									type: 'audio'
										// #ifdef H5
										,
									name
									// #endif
								}
							})

							let {
								recorder_order_id: order_id
							} = this
							await this.$api.technician.recordingAdd({
								order_id,
								link
							})
							this.$util.hideAll()
						},
						// #ifdef H5
						handlerSuccess(res) {
							this.updateOrderItem({
								key: 'recorder',
								val: res
							})
						},
						handlerError(code) {
							switch (code) {
								case '101':
									uni.showModal({
										content: '当前浏览器版本较低，请更换浏览器使用，推荐在微信中打开。'
									})
									break;
								case '201':
									uni.showModal({
										content: '麦克风权限被拒绝，请刷新页面后授权麦克风权限。'
									})
									break
								default:
									uni.showModal({
										content: '未知错误，请刷新页面重试'
									})
									break
							}
						},
						// #endif 
						// 拒绝接单
						async toRefuse(index) {
							// this.index = index
							// this.coach_refund_text = ''
							// this.$refs.refuse_item.open()
							this.toConfirm(index, -1)
						},
						// 确认：拒绝接单
						async confirmRefuse() {
							let {
								coach_refund_text
							} = this
							coach_refund_text = coach_refund_text.length > 0 ? coach_refund_text.replace(
								/(^\s*)|(\s*$)/g,
								"") : ''
							if (coach_refund_text.length == 0) {
								this.$util.showToast({
									title: `请输入拒单原因`
								})
								return
							}
							this.coach_refund_text = this.coach_refund_text.substring(0, 200)
							let {
								index,
							} = this
							this.toConfirm(index, -1)
						},
						// type: -1拒绝接单，3确定接单，4已出发，5已到达，6开始服务，7已完成
						async toConfirm(index, type) {
							if (this.lockTap) return
							let {
								id: order_id,
							} = this.list.data[index]
							order_id = order_id * 1
							let param = {
								order_id,
								type
							}
							if (type == -1) {
								param.coach_refund_text = this.coach_refund_text
							}
							this.toConfirmUpdate(index, type, param)
						},
						async toConfirmUpdate(index, type, param, location = {}) {
							let msg = {
								'-1': '已拒绝接单',
								3: '接单成功',
								4: '已成功出发',
								5: '已成功到达',
								6: '已开始服务',
								7: '服务已完成'
							}
							if (this.lockTap) return
							this.lockTap = true

							let {
								plugAuth,
								service_recording_show
							} = this.configInfo
							let {
								recording
							} = plugAuth

							let {
								isUserMedia,
								recorder_order_id,
								recorder_status
							} = this

							// #ifndef H5
							isUserMedia = 1
							// #endif

							let flag = true

							let {
								order_id
							} = param

							let order_info = {}
							try {
								order_info = await this.$api.technician.dispatchOrderInfo({
									order_id
								})
							} catch (e) {
								if (type == -1) {
									this.$refs.refuse_item.close()
								}
								this.param.page = 1
								this.getList()
								this.lockTap = false
								this.$util.hideAll()
								return
							}

							this.$util.showLoading()

							if (!flag) {
								this.lockTap = false
								this.$util.hideAll()
								return
							}

							try {
								if (type == -1) {
									this.$refs.refuse_item.close()
								}
								await this.$api.technician.dispatchUpdateOrder(param)
								this.list.data.splice(index, 1)
								
								
								this.$util.hideAll()
								this.$util.showToast({
									title: msg[type]
								})
								await this.getList(true)
								this.updateOrderItem({
									key: 'haveOperItem',
									val: true
								})
								setTimeout(() => {
									this.lockTap = false
								}, 500)
							} catch (e) {
								this.updateOrderItem({
									key: 'haveOperItem',
									val: true
								})
								setTimeout(() => {
									this.param.page = 1
									this.getList()
									this.lockTap = false
									this.$util.hideAll()
								}, 2000)
							}
						},
						
						// 订单详情
						goDetail(index) {
							let {
								id
							} = this.list.data[index]
							this.list.data[index].is_show_more = false
							let url = `/technician/pages/task/detail?id=${id}`
							this.$util.goUrl({
								url
							})
						},
						toLabel(index) {}
					}
		}
</script>


<style lang="scss">
	.technician-pages-order {
		.list-item {
			margin: 20rpx 28rpx 0 28rpx;
			box-shadow: 0px 2px 20px 0px rgba(0, 0, 0, 0.05);

			.nav-title {
				width: 100%;
				height: 90rpx;
				padding: 0 28rpx;
				border-radius: 16rpx 16rpx 0 0;
				color: #999999;
				background: linear-gradient(270deg, rgba(153, 153, 153, 0) 0%, rgba(153, 153, 153, 0.15) 100%);

				.iconfont {
					font-size: 36rpx;
				}
			}

			.danger {
				color: #FF4000;
				background: linear-gradient(270deg, rgba(255, 64, 0, 0) 0%, rgba(255, 64, 0, 0.15) 99%);
			}

			.warning {
				color: #FF9500;
				background: linear-gradient(270deg, rgba(255, 149, 0, 0) 0%, rgba(255, 149, 0, 0.15) 100%);
			}

			.success {
				color: #009900;
				background: linear-gradient(270deg, rgba(0, 153, 0, 0) 0%, rgba(0, 153, 0, 0.15) 100%);
			}

			.abnormal-btn {
				width: 108rpx;
				height: 40rpx;
				background: #FFEBE5;
				border-radius: 6rpx;
				color: #FF4000;
			}

			.count-list {
				width: 100%;
				height: 130rpx;
				background: #FAFAFA;
				border-radius: 18rpx;
				padding-left: 28rpx;

				.count-item {
					width: 37%;

					.flex-y-baseline {
						margin: 4rpx 0 6rpx 0;

						.f-md-title {
							margin-left: 5rpx;
						}
					}
				}

				.count-item:nth-child(3) {
					width: 26%
				}
			}

			.oper-btn {
				width: 174rpx;
				height: 72rpx;
				border-radius: 36rpx;
				border: 1rpx solid #fff;
			}

			.oper-btn.sm {
				border: 1rpx solid #999;
			}

			.oper-btn:nth-child(2) {
				margin-left: 20rpx;
			}
		}
	}

	.show-more-tag {
		width: 20rpx;
		height: 20rpx;
		top: 70rpx;
		left: 50%;
		margin-left: -10rpx;
		background: #FFFFFF;
		transform: rotate(45deg);
		box-shadow: 0 0 4px 4px rgba(222, 222, 222, 0.37);
		z-index: 99990;
	}

	.show-more-info {
		top: 80rpx;
		right: -71rpx;
		width: 200rpx;
		background: #FFFFFF;
		box-shadow: 0px 6px 16px 0px rgba(222, 222, 222, 0.37);
		border-radius: 8px;
		border: 1px solid #F5F5F5;
		z-index: 99999;

		.more-item {
			padding: 24rpx 0;
		}
	}
</style>